package com.study.spring_ai.config;

import com.alibaba.cloud.ai.memory.redis.RedisChatMemoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.converter.BeanOutputConverter;
import org.springframework.ai.converter.StructuredOutputConverter;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.template.st.StTemplateRenderer;
import org.springframework.ai.vectorstore.RedisVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;
import java.util.Map;

@Configuration
public class FullStackAiConfig {

    // 1. 核心模型配置（以DeepSeek为例）
//    @Bean
//    public ChatModel deepSeekModel(@Value("${spring.ai.dashscope.api-key}") String apiKey) {
//        return new DeepSeekChatModel(apiKey);
//    }


//     2. 向量库配置（RAG知识库）
    @Bean
        public VectorStore vectorStore(EmbeddingModel embeddingModel) {

        return new RedisVectorStore(RedisVectorStore
                .RedisVectorStoreConfig
                .builder()
                .withURI("redis://192.168.18.201:6379")
                .build()
                ,embeddingModel,false); // 支持FAISS/Redis等
    }

    // 3. 对话记忆存储（Redis持久化）
    @Bean
    public ChatMemory chatMemory() {
        return MessageWindowChatMemory
                .builder()
                .maxMessages(10)
                .chatMemoryRepository(
                        new RedisChatMemoryRepository
                                .RedisBuilder()
                                .host("192.168.18.201")
                                .port(6379)
                                .password("123456")
                                .build()).build();
    }

    // 4. 全功能ChatClient（核心配置）
    @Bean
    public ChatClient aiAssistant(ChatClient.Builder builder,
                                  VectorStore vectorStore,
                                  ChatMemory chatMemory) {
        //动态模版示例  动态模版是通过stringTemplate引擎生成，支持变量替换，如：{name}、{voice}
//        String userText = """
//            Tell me about three famous pirates from the Golden Age of Piracy and why they did.
//            Write at least a sentence for each pirate.
//            """;
//
//        Message userMessage = new UserMessage(userText);
//
//        String systemText = """
//      You are a helpful AI assistant that helps people find information.
//      Your name is {name}
//      You should reply to the user's request with your name and also in the style of a {voice}.
//      """;
//
//        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
//        Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
//
//        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

        return builder
                // 4.1 提示词工程：全局角色+动态模板
                .defaultSystem("""
                        你是{company}的{role}，回答需满足：
                        **知识库**：优先使用<知识>标签内容
                        **思考要求**：{reasoning}
                        === 知识 ===
                        {rag_context}
                        """)
                // 4.2 RAG集成：检索增强生成
//                .defaultAdvisors(new QuestionAnswerAdvisor(vectorStore)) // 返回Top3文档[1,6](@ref)
                // 4.3 聊天记忆：多轮对话支持
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
//                // 4.4 工具调用：注册外部函数
//                .defaultToolCallbacks()
//                .defaultFunction("get_weather", "查询实时天气",
//                        (location) -> weatherService.getForecast(location))
                // 4.5 模型参数优化
                .defaultOptions(ChatOptions.builder().temperature(0.3)
                        .maxTokens(1000)
                        .build())
                .defaultTemplateRenderer(StTemplateRenderer.builder().build()) //设置默认模版渲染器  默认为stringTemplate
                .build();
    }

//    // 5. 评估埋点（监控与评估）
//    @Bean
//    public ChatClientAspect monitoringAspect(MeterRegistry registry) {
//        return new ChatClientAspect(registry); // 监控令牌消耗/响应延迟[6](@ref)
//    }
}